﻿using System.Linq;
using System.Web.Mvc;
using System.Collections.Generic;
using Ecommerce.Models;
using Library;
using Library.Models;
using Library.MVCHelpers;
using PagedList;

namespace Ecommerce.Controllers
{
    [Compress(Order = 1)]
    [OutputCache(CacheProfile = "Cache60s", Order = 2)]
    public class ProductCategoryController : BaseController
    {
        private const int ProductPageSize = 20;
        public ActionResult Index(string categoryUrl, int? page)
        {
            if (NOWCulture.IsCulture(categoryUrl))
            {
                NOWCulture.UpdateCurrentCulture(categoryUrl);
                return RedirectPermanent("~/");
            }

            var categoryUrlInfo = SEOHelper.GetURLInfo(categoryUrl);
            int pageNumber = (page ?? 1);

            //Not found
            if (categoryUrlInfo == null || categoryUrlInfo.URLType != URLTypes.ProductCategory)
            {
                return HttpNotFound();
            }

             using(var db = DatabaseConnector)
            {
                var productCategory = db.ProductCategories.SingleOrDefault(i => i.Id == categoryUrlInfo.ModelId);
                 //Use ViewBag.ProductCategoryCulture to show productCategory's link, productCategory's title, productCategory's name
                var productCategoryCulture = productCategory.ProductCategoryCultures.SingleOrDefault(i => i.Culture == NOWCulture.CurrentCulture) ?? productCategory.ProductCategoryCultures.First();
                ViewBag.ProductCategoryCulture = productCategoryCulture;


                var products = productCategory.Products;
                List<ProductViewModel> lstProductViewModels = new List<ProductViewModel>();

                foreach (var item in products)
                {
                    ProductViewModel productViewModel = new ProductViewModel(item);
                    lstProductViewModels.Add(productViewModel);
                }

                return View(lstProductViewModels.ToPagedList(pageNumber, ProductPageSize));
            }
        }
    }
}